﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using YiSha.Business.Cache;
using YiSha.Data.Repository;
using YiSha.Entity.SystemManage;
using YiSha.Enums;
using YiSha.Model.Param.SystemManage;
using YiSha.Model.Result.SystemManage;
using YiSha.Service.SystemManage;
using YiSha.SqlSugars;
using YiSha.Util;
using YiSha.Util.Model;

namespace YiSha.Service.SystemManage
{
    public class DataDictService : RepositoryFactory
    {
        public DataDictDetailService DataDictDetailService { get; set; }
        public DataDictCache DataDictCache { get; set; }
        public DataDictDetailCache DataDictDetailCache { get; set; }

        #region 获取数据
        public async Task<TData<List<DataDictEntity>>> GetList(DataDictListParam param)
        {
            var obj = new TData<List<DataDictEntity>>();
            var expression = ListFilter(param);
            var list = SqlSugarAdapters.GetList(expression);
            obj.Data = list;
            return obj;
        }

        public async Task<TData<List<DataDictEntity>>> GetPageList(DataDictListParam param, Pagination pagination)
        {
            var obj = new TData<List<DataDictEntity>>();
            var expression = ListFilter(param);
            var list = SqlSugarAdapters.GetPager(expression, pagination);
            obj.Total = list.Item1;
            obj.Data = list.Item2;
            return obj;
        }

        public async Task<DataDictEntity> GetEntity(string id)
        {
            return SqlSugarAdapters.GetEntity<DataDictEntity>(s => s.Id == id);
        }

        public async Task<int> GetMaxSort()
        {
            object result = SqlSugarAdapters.SqlQueryCount("SELECT MAX(DictSort) FROM SysDataDict");
            int sort = result.ParseToInt();
            sort++;
            return sort;
        }

        public bool ExistDictType(DataDictEntity entity)
        {
            var expression = ExtLinq.True<DataDictEntity>();
            expression = expression.And(t => t.Valid);
            if (entity.Id.IsEmpty())
            {
                expression = expression.And(t => t.DictType == entity.DictType);
            }
            else
            {
                expression = expression.And(t => t.DictType == entity.DictType && t.Id != entity.Id);
            }
            return SqlSugarAdapters.GetList(expression).Count() > 0 ? true : false;
        }

        /// <summary>
        /// 是否存在字典值
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool ExistDictDetail(string dictType)
        {
            var expression = ExtLinq.True<DataDictDetailEntity>();
            expression = expression.And(t => t.DictType == dictType);
            return SqlSugarAdapters.GetList(expression).Count() > 0 ? true : false;
        }
        #endregion

        #region 提交数据
        public async Task<TData> SaveForm(DataDictEntity entity)
        {
            TData obj = new TData();
            var db = SugarBase.GetInstance();
            try
            {
                //开始事务
                db.BeginTran();
                if (ExistDictType(entity))
                {
                    obj.Msg = "字典类型已经存在！";
                    obj.MsgCode = MsgCode.Fail;
                    return obj;
                }
                if (!entity.Id.IsEmpty())
                {
                    var dbEntity = db.Queryable<DataDictEntity>().Where(w => w.Id == entity.Id).First();
                    if (!dbEntity.IsEmpty() && dbEntity.DictType != entity.DictType)
                    {
                        // 更新子表的DictType，因为2个表用DictType进行关联
                        IEnumerable<DataDictDetailEntity> detailList = SqlSugarAdapters.GetList<DataDictDetailEntity>(p => p.DictType == dbEntity.DictType);
                        foreach (DataDictDetailEntity detailEntity in detailList)
                        {
                            detailEntity.DictType = entity.DictType;
                            await detailEntity.Modify();
                        }
                    }
                    dbEntity.DictType = entity.DictType;
                    dbEntity.Remark = entity.Remark;
                    dbEntity.DictSort = entity.DictSort;
                    await dbEntity.Modify();
                    db.Updateable<DataDictEntity>(dbEntity).ExecuteCommand();
                }
                else
                {
                    await entity.Create();
                    db.Insertable<DataDictEntity>(entity).ExecuteCommand();
                }
                //提交事务
                db.CommitTran();
            }
            catch(Exception ex)
            {
                obj.Msg = ex.Message;
                obj.MsgCode = MsgCode.Fail;
                //回滚
                db.RollbackTran();
            }
            return obj;
        }

        public async Task<TData> DeleteForm(List<string> ids)
        {
            TData obj = new TData();
            var info = SqlSugarAdapters.GetList<DataDictEntity>(s => ids.Contains(s.Id));
            if (info.Count > 0)
            {
                SqlSugarAdapters.Delete<DataDictEntity>(s => ids.Contains(s.Id));
            }
            else
            {
                obj.MsgCode = MsgCode.Fail;
                obj.Msg = "当前数据不存在";
            }
            SqlSugarAdapters.Delete<MenuEntity>(s => ids.Contains(s.Id));
            obj.MsgCode = MsgCode.Success;
            return obj;
        }
        #endregion

        #region 私有方法
        private Expression<Func<DataDictEntity, bool>> ListFilter(DataDictListParam param)
        {
            var expression = ExtLinq.True<DataDictEntity>();
            if (param != null)
            {
                if (!param.DictType.IsEmpty())
                {
                    expression = expression.And(t => t.DictType.Contains(param.DictType));
                }
                if (!param.Remark.IsEmpty())
                {
                    expression = expression.And(t => t.Remark.Contains(param.Remark));
                }
            }
            return expression;
        }
        #endregion
    }
}
